﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using ExpressionType=System.Linq.Expressions.ExpressionType;
using MemberExpression=System.Linq.Expressions.MemberExpression;
using UnaryExpression=System.Linq.Expressions.UnaryExpression;

namespace CommonExtensions.ExpressionExtensions.OfFunc
{
    public static class Extensions
    {
        public static string GetPropertyName<T>(this Expression<Func<T,object>> expression)
        {
            MemberExpression memberExpression = null;

            if (expression.Body.NodeType == ExpressionType.Convert)
            {
                var body = (UnaryExpression) expression.Body;
                memberExpression = body.Operand as MemberExpression;
            }
            else if (expression.Body.NodeType == ExpressionType.MemberAccess)
            {
                memberExpression = expression.Body as MemberExpression;
            }

            if (memberExpression == null) throw new ArgumentException("Not a member access expression", "expression");

            return memberExpression.Member.Name;
        }
    }
}